import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import '../utils/http_client.dart';

class UpdateService {
  static Future<void> checkUpdate(BuildContext context) async {
    try {
      // 获取当前版本
      final packageInfo = await PackageInfo.fromPlatform();
      final localVersion = packageInfo.version;

      // 请求服务器版本
      final response = await HttpClient.dio.post('/follower/checkUpdate');
      print(response.data);
      if (response.data['code'] == 0) {
        final serverData = response.data;
        final serverVersion = serverData['data']['version'];
        final downloadUrl = serverData['data']['url'];
        final message = serverData['msg'];
        final force = serverData['data']['force'] == true;
        print("$localVersion,$serverVersion");


        // 比较版本号
        if (_compareVersion(localVersion, serverVersion) < 0) {
          if (context.mounted) {
            await _showUpdateDialog(
              context: context,
              force: force,
              message: message,
              downloadUrl: downloadUrl,
            );
          }
        }
      }
    } catch (e) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('检查更新失败')),
        );
      }
    }
  }

  static Future<void> _showUpdateDialog({
    required BuildContext context,
    required bool force,
    required String message,
    required String downloadUrl,
  }) async {
    void showUpdateDialogImpl() {
      showDialog<bool>(
        context: context,
        barrierDismissible: !force,
        builder: (context) => WillPopScope(
          onWillPop: () async => !force,
          child: AlertDialog(
            title: const Text('更新提示'),
            content: Text(message),
            actions: [
              if (!force)
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('稍后再说'),
                ),
              ElevatedButton(
                onPressed: () async {
                  Navigator.pop(context);
                  await _downloadAndInstall(downloadUrl);
                },
                child: const Text('立即更新'),
              ),
            ],
          ),
        ),
      ).then((value) {
        // 如果是强制更新且用户点击了关闭，则再次显示弹窗
        if (force && value == null) {
          showUpdateDialogImpl();
        }
      });
    }

    showUpdateDialogImpl();
  }

  static Future<void> _downloadAndInstall(String url) async {
    try {
      final uri = Uri.parse(url);
      if (await canLaunchUrl(uri)) {
        await launchUrl(
          uri,
          mode: LaunchMode.externalApplication,
        );
      }
    } catch (e) {
      debugPrint('下载安装失败: $e');
    }
  }

  static int _compareVersion(String v1, String v2) {
    print(v1);
    print(v2);
    final v1Parts = v1.split('.').map(int.parse).toList();
    final v2Parts = v2.split('.').map(int.parse).toList();

    for (var i = 0; i < v1Parts.length || i < v2Parts.length; i++) {
      final v1Part = i < v1Parts.length ? v1Parts[i] : 0;
      final v2Part = i < v2Parts.length ? v2Parts[i] : 0;
      if (v1Part > v2Part) return 1;
      if (v1Part < v2Part) return -1;
    }
    return 0;
  }
}